import React, { useState } from 'react'

export default function Cart() {
    const [list, setList] = React.useState([
        { selected: true, name: "苹果", price: 10, num: 2, id: 0 },
        { selected: false, name: "香蕉", price: 2, num: 1, id: 1 },
        { selected: false, name: "西红柿", price: 11, num: 3, id: 2 },
    ])
    const [name,setName] = React.useState("张三")
    function checkboxChanged(index){
        list[index].selected = !list[index].selected;
        console.log("list",list)
        /**
         * 针对引用类型的数据，必须把引用地址本身修改了，否则界面不会更新
         * 
         */
        setList([...list])
    }
    function changeNum(index,n){
        list[index].num += n;
        setList([...list])
    }
    function del(index){
        list.splice(index,1);
        setList([...list])
    }
  const total =   React.useMemo(()=>{
        //计算过程在这里，需要返回计算后的数据
        console.log("重新计算总价")
        let t = 0;
        list.filter(item=>item.selected).forEach(item=>{
           t +=  item.price * item.num
        })
        return t;
    },[list])
    console.log("cart")
    return (
        <div>
            {name} <button onClick={()=>setName("王二麻子")}>修改名字</button>
            <table>
                <thead>
                    <tr>
                        <th><input type="checkbox" /></th>
                        <th>商品名</th>
                        <th>单价</th>
                        <th>数量</th>
                        <th>小计</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    {
                        list.map((item,index) => {
                            return <tr key={item.id}>
                                <td><input onChange={()=>checkboxChanged(index)} checked={item.selected} type='checkbox' /></td>
                                <td>{item.name}</td>
                                <td>{item.price}</td>
                                <td>
                                    <button disabled={item.num === 1} onClick={()=>changeNum(index,-1)}>-</button>
                                    {item.num}
                                    <button onClick={()=>changeNum(index,1)}>+</button>
                                </td>
                                <td>{item.price * item.num}</td>
                                <td><button onClick={()=>del(index)}>删除</button></td>
                            </tr>
                        })
                    }

                </tbody>
            </table>
            总价：{total}
        </div>
    )
}
